package com.shujia.wyh.day27.network.tcpcoding;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo2 {
    public static void main(String[] args) throws Exception {
        //创建服务器端的Socket对象
        ServerSocket ss = new ServerSocket(12345);

        //监听客户端的连接
        Socket socket = ss.accept();

        //获取通道中的输入流对象，接收客户端发送的信息
        InputStream is = socket.getInputStream();
        //获取通道中的输出流对象，写反馈给客户端
        OutputStream os = socket.getOutputStream();

        while (true) {
            byte[] bytes = new byte[1024];
            int length = is.read(bytes);
            String s = new String(bytes, 0, length);

            //获取客户端的ip和主机名
            InetAddress address = socket.getInetAddress();
            String ip = address.getHostAddress();
            String hostName = address.getHostName();
            System.out.println(ip + "," + hostName + "发送的数据为：" + s);

            //写反馈给客户端
            os.write("服务器已经收到数据！！".getBytes());
        }
    }
}
